<script setup lang="ts">
import type { PopoverInstance } from 'element-plus'
import type { Notice } from '@/apis/system/noticeApi'
import { Icon } from '@iconify/vue'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { noticeApi } from '@/apis/system/noticeApi'

const notices = ref<Notice[]>([])
onMounted(loadData)
async function loadData() {
  const data = await noticeApi.queryPage({ state: 'UNREAD', orderBy: 'id', orderAsc: false, size: 5 })
  notices.value = data.records ?? []
}
const router = useRouter()
const popoverRef = ref<PopoverInstance>()
async function onClick(data: Notice) {
  await noticeApi.modifyState({ id: data.id!, state: 'READ' })
  if (data.link) {
    jump(data.link)
  }
}
function jump(path: string) {
  popoverRef.value?.hide()
  router.push(path)
}
</script>

<template>
  <el-popover
    ref="popoverRef"
    placement="bottom-end"
    :popper-style="{ padding: 0 }"
    width="300px"
  >
    <template #reference>
      <el-badge :is-dot="notices && notices.length > 0" :offset="[-10, 10]" class="header-icon">
        <Icon icon="tdesign:notification" />
      </el-badge>
    </template>

    <div v-if="notices && notices.length > 0" class="flex flex-col">
      <template v-for="(notice, index) in notices" :key="notice.id">
        <div class="cursor-pointer p-2 hover-bg-active" @click="onClick(notice)">
          <div class="text-sm font-bold">
            {{ notice.title }}
          </div>
          <div class="py-1 indent-4 text-xs">
            {{ notice.content }}
          </div>
          <div class="flex flex-row justify-end text-xs">
            {{ notice.createTime }}
          </div>
        </div>
        <el-divider v-if="index < notices.length - 1" style="margin: 0px;" />
      </template>
    </div>
    <div v-else class="h-32 flex items-center justify-center">
      暂无最新消息
    </div>
    <el-divider style="margin: 0px;" />
    <div class="h-10 flex cursor-pointer items-center justify-center hover-bg-active" @click="jump('/home/notice')">
      查看全部
    </div>
  </el-popover>
</template>

<style scoped>
.header-icon {
  --at-apply: h-4 w-4 p-2 rounded-full cursor-pointer hover-bg-active;
}
</style>
